package filter;

import servlet.Login;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "permissionFilter",urlPatterns = "/*")
public class permissionFilter implements Filter{

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest hsr=(HttpServletRequest) servletRequest;
        HttpServletResponse hsrp=(HttpServletResponse) servletResponse;

        String spath=hsr.getServletPath();

      /*  String flag=(String)hsr.getSession().getAttribute("msg");
        System.out.println("flag------>"+flag);*/

        if(spath!=null && (spath.equals("/index.jsp") || spath.equals("/Login") ||spath.equals("/Logout"))){
            //System.out.println("1");
            filterChain.doFilter(servletRequest,servletResponse);
        }else{
/*            if(flag.equals("登陆成功！") || Login.flag){
                System.out.println("2");
                filterChain.doFilter(servletRequest,servletResponse);
            }else if(flag.equals("请填写完整信息！")){
                //hsr.setAttribute("loginTip","请填写完整信息！");
                System.out.println("3");
                hsr.getRequestDispatcher("/index.jsp").forward(hsr,hsrp);
            }else if(flag.equals("账号或者密码不正确，请重新登陆！") ){
                //hsr.setAttribute("loginTip","账号或者密码不正确，请重新登陆！");
                System.out.println("4");
                hsr.getRequestDispatcher("/index.jsp").forward(hsr,hsrp);
            }else{
                    //hsr.setAttribute("loginTip","请先登录！");
                    System.out.println("5");
                    hsr.getRequestDispatcher("/index.jsp").forward(hsr,hsrp);
                }*/

            if(Login.flag){
                System.out.println("yes");
                filterChain.doFilter(servletRequest,servletResponse);
            }else{
                //hsr.setAttribute("loginTip","请先登录！");
                System.out.println("no");
                hsr.getRequestDispatcher("/index.jsp").forward(hsr,hsrp);
                //hsrp.sendRedirect("/index.jsp");
            }


        }
    }


    @Override
    public void destroy() {

    }
}
